package net.hserver.admin.system.common;

import com.mybatisflex.core.paginate.Page;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 统一返回体
 *
*
 * @since 2020/3/18 18:50
 */
@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class MyResult {
    /**
     * 状态码
     */
    private MyCode code;
    /**
     * 状态说明
     */
    private String message;
    /**
     * 错误信息
     */
    private String exception;
    /**
     * 数据
     */
    private Collection<?> data;
    /**
     * 总条数
     */
    private Long total;
    /**
     * 当前页
     */
    private Long index;
    /**
     * 页大小
     */
    private Long limit;

    public MyResult(MyCode code) {
        this.code = code;
        this.message = code.getMsg();
    }

    public static MyResult of(Page<?> data) {
        return code(MyCode.SUCCESS)
                .setData(data.getRecords())
                .setIndex(data.getPageNumber())
                .setLimit(data.getPageSize())
                .setTotal(data.getTotalRow());
    }

    public static MyResult of(Collection<?> data) {
        Collection<?> list = CollectionUtils.isEmpty(data) ? Collections.emptyList() : data;
        return code(MyCode.SUCCESS)
                .setData(list)
                .setTotal((long) list.size());
    }

    public static MyResult of(Object data) {
        List<Object> list = Objects.isNull(data) ? Collections.emptyList() : Collections.singletonList(data);
        return code(MyCode.SUCCESS)
                .setData(list)
                .setTotal((long) list.size());
    }

    public static MyResult success() {
        return code(MyCode.SUCCESS);
    }

    public static MyResult failure() {
        return code(MyCode.FAILURE);
    }

    public MyResult setCode(MyCode code) {
        this.code = code;
        this.message = code.getMsg();
        return this;
    }

    public static MyResult code(MyCode code) {
        return new MyResult().setCode(code);
    }

}
